<template>
  <biz-wrap-simple>
    <div class="site-wrapper site-page--login">
      <div class="site-content__wrapper">
        <div class="site-content">
          <div class="brand-info">
            <h2 class="brand-info__text">
              优速搭<gd-icon :icon-name="'emojione:rocket'"></gd-icon>
            </h2>
            <p class="brand-info__intro">
              优速搭,一款支持高代码、低代码、零代码的多端适配的全栈开发框架。
            </p>
          </div>
          <div class="login-main">
            <!-- <h3 class="login-title">欢迎使用</h3> -->
            <!-- <el-radio-group
              style="
                width: 100%;
                text-align: center;
                margin: 0 0 20px 200px;
                display: flex;
                align-items: center;
              "
              v-model="submitFormType"
              @change="onChangeSubmitFormType"
            >
              <el-radio :label="'login'">登录</el-radio>
              <el-radio :label="'register'">注册</el-radio>
            </el-radio-group> -->
            <template v-if="submitFormType === 'login'">
              <el-form
                ref="refDataForm"
                :model="dataForm[submitFormType]"
                :rules="dataRule[submitFormType]"
                label-width="95px"
                status-icon
                @keyup.enter.native="dataFormSubmit()"
              >
                <!-- <el-form-item prop="username" label="邮箱">
                  <el-input
                    v-model="dataForm[submitFormType].username"
                    placeholder="邮箱"
                  />
                </el-form-item>
                <el-form-item prop="password" label="密码">
                  <el-input
                    v-model="dataForm[submitFormType].password"
                    type="password"
                    show-password
                    placeholder="密码"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button
                    class="btn-submit"
                    type="primary"
                    @click="dataFormSubmit()"
                    >登录
                  </el-button>
                </el-form-item> -->
                <el-form-item>
                  <el-button
                    class="login-btn-submit"
                    type="primary"
                    @click="loginInOAth2"
                    >DCloud账号登录
                  </el-button>
                </el-form-item>
              </el-form>
            </template>
            <template v-else>
              <el-form
                ref="refDataForm"
                :model="dataForm[submitFormType]"
                :rules="dataRule[submitFormType]"
                label-width="95px"
                status-icon
              >
                <el-form-item prop="username" label="邮箱">
                  <el-input
                    v-model="dataForm[submitFormType].username"
                    placeholder="邮箱"
                  >
                    <template #append>
                      <span
                        :style="curVerifycodeSenderConfig.style"
                        @click="onSendEmailVerifyCode"
                        >{{ curVerifycodeSenderConfig.text }}</span
                      >
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="verifycode" label="邮箱验证码">
                  <el-input
                    v-model="dataForm[submitFormType].verifycode"
                    placeholder="邮箱验证码"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                  <el-input
                    v-model="dataForm[submitFormType].password"
                    type="password"
                    show-password
                    placeholder="密码"
                  />
                </el-form-item>
                <el-form-item prop="checkpass" label="确认密码">
                  <el-input
                    v-model="dataForm[submitFormType].checkpass"
                    type="password"
                    show-password
                    placeholder="确认密码"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    class="btn-submit"
                    type="primary"
                    @click="dataFormSubmit()"
                    >注册
                  </el-button>
                </el-form-item>
              </el-form>
            </template>
          </div>
        </div>
      </div>
    </div>
  </biz-wrap-simple>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import {
  isSuccessReqBackend,
  getErrorMsgReqBackend,
  getBackendData,
} from "@/config/utils";
import { globalConfig } from "@uni_modules/gd-accbuild-core/config";
import { testTools } from "@uni_modules/gd-accbuild-core/config/utils";
import { login, sendVerifycode, register } from "@/services/sys";
import gdToastService from "@uni_modules/gd-accbuild-core/components/gd-accbuild-ui/gd-ui/gd-service/gd-toast-service/gd-toast-service";
import { useStore } from "@gd-accbuild-core/store/hackVueStore";
const submitFormType = ref("login");
const dataForm = reactive({
  login: {
    username: "",
    password: "",
  },
  register: {
    username: "",
    verifycode: "",
    password: "",
    checkpass: "",
  },
});
const validateUsername = (rule, value, callback) => {
  if (!testTools.testEmail(value)) {
    callback(new Error("邮箱格式不正确"));
  } else {
    callback();
  }
};
const validatePass = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error("密码必须大于6位"));
  } else {
    callback();
  }
};
const validateCheckPass = (rule, value, callback) => {
  if (value !== dataForm.register.password) {
    callback(new Error("两次输入的密码不相等"));
  } else {
    callback();
  }
};
const validateVerifycode = (rule, value, callback) => {
  if (!value) {
    callback(new Error("邮箱验证码必填"));
  } else {
    callback();
  }
};
const dataRule = reactive({
  login: {
    username: [
      {
        required: true,
        validator: validateUsername,
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        validator: validatePass,
        trigger: "blur",
      },
    ],
  },
  register: {
    username: [
      {
        required: true,
        validator: validateUsername,
        trigger: "blur",
      },
    ],
    verifycode: [
      {
        required: true,
        validator: validateVerifycode,
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        validator: validatePass,
        trigger: "blur",
      },
    ],
    checkpass: [
      {
        required: true,
        validator: validateCheckPass,
        trigger: "blur",
      },
    ],
  },
});
const refDataForm = ref(null);
/* setInterval(() => {
	  ElMessage({
	    message: "555555555555",
	    type: "warning",
	    //appendTo:document.getElementsByTagName("uni-page")[0]
	  });
	}, 10000); */
const _store = useStore();
const dataFormSubmit = async () => {
  const isValid = await refDataForm.value.validate();
  if (isValid) {
    const doSubmit = submitFormType.value === "login" ? login : register;
    const res = await doSubmit(dataForm[submitFormType.value]);
    if (!isSuccessReqBackend(res)) {
      gdToastService({
        message: getErrorMsgReqBackend(res),
        type: "error",
      });
      return;
    }
    uni.setStorageSync("uni_id_token", res.tokenInfo.token);
    uni.setStorageSync("uni_id_token_expired", res.tokenInfo.tokenExpired);
    uni.setStorageSync("userInfo", JSON.stringify(getBackendData(res)));
    const homePageInfo = _store.state.permission.pages.find(
      (page) => page.uiOptions?.pageTypeFlag === "Home"
    );
    console.log(_store.state.permission.pages);
    if (homePageInfo) {
      uni.navigateTo({
        url: homePageInfo.targetResourceUrl,
      });
    } else {
      gdToastService({
        message: "首页未设置",
        type: "warning",
      });
    }
  }
};
const onChangeSubmitFormType = (val) => {
  setTimeout(() => {
    refDataForm.value.resetFields();
  }, 0);
};

const verifycodeSenderConfigs = [
  {
    text: "发送验证码",
    style: {
      cursor: "pointer",
    },
  },
  {
    text: "验证码已发送",
    style: {
      cursor: "not-allowed",
    },
  },
];
const curVerifycodeSenderConfig = ref(verifycodeSenderConfigs[0]);
const onSendEmailVerifyCode = async () => {
  const validateRes = await refDataForm.value.validateField("username");
  if (!validateRes) {
    return;
  }
  if (curVerifycodeSenderConfig.value.text === "发送验证码") {
    curVerifycodeSenderConfig.value = verifycodeSenderConfigs[1];
    const res = await sendVerifycode(dataForm.register);
    if (isSuccessReqBackend(res)) {
      gdToastService({
        message: getErrorMsgReqBackend(res),
        type: "success",
      });
    }
  }
};

const loginInOAth2 = () => {
  ///pages/gd-accbuild-development-mgr/home/index?
  let curPageInfo = _store.state.permission.pages.find(
    (page) => page.uiOptions.pageTypeFlag === "Home"
  ); //  `${globalConfig.BASE_ROUTER_PREFIX_PATH}${globalConfig.ROUTER_MODE === "hash" ? "/#" : ""}${url}`
  window.location.href = `https://account.dcloud.net.cn/oauth2/webAuthorize?client_id=${
    globalConfig.OAUTH_INFO["client_id"]
  }&redirect_uri=${encodeURIComponent(
    `${location.origin}${globalConfig.BASE_ROUTER_PREFIX_PATH}${
      globalConfig.ROUTER_MODE === "hash" ? "/#" : ""
    }${curPageInfo.targetResourceUrl}`
  )}&response_type=code`;
};
const clearLoginToken = () => {
  uni.removeStorageSync("uni_id_token");
  uni.removeStorageSync("uni_id_token_expired");
};
clearLoginToken();
</script>

<style lang="scss" scoped>
.site-wrapper.site-page--login {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(38, 50, 56, 0.6);
  overflow: hidden;

  &:before {
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1;
    width: 100%;
    height: 100%;
    content: "";
    background-image: url(~@/static/images/login_bg.jpg);
    background-size: cover;
  }

  .site-content__wrapper {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 0;
    margin: 0;
    overflow-x: hidden;
    overflow-y: auto;
    background-color: transparent;
  }

  .site-content {
    min-height: 100%;
    padding: 30px 500px 30px 30px;
  }

  .brand-info {
    margin: 220px 100px 0 90px;
    color: #fff;
  }

  .brand-info__text {
    margin: 0 0 22px 0;
    font-size: 48px;
    font-weight: 400;
    text-transform: uppercase;
  }

  .brand-info__intro {
    margin: 10px 0;
    font-size: 16px;
    line-height: 1.58;
    opacity: 0.6;
  }

  .login-main {
    position: absolute;
    top: 0;
    right: 0;
    padding: 150px 60px 180px;
    width: 470px;
    min-height: 100%;
    background-color: #fff;
  }

  .login-title {
    font-size: 16px;
  }

  .login-captcha {
    overflow: hidden;

    > img {
      width: 100%;
      cursor: pointer;
    }
  }

  .btn-submit {
    width: 100%;
    margin-top: 20px;
  }
}
</style>
